package record

import (
	"fmt"
	"time"

	"sigs.k8s.io/controller-runtime/pkg/client"

	bkemetrics "gopkg.openfuyao.cn/cluster-api-provider-bke/pkg/metrics"
	"gopkg.openfuyao.cn/cluster-api-provider-bke/utils"
	"gopkg.openfuyao.cn/cluster-api-provider-bke/utils/config"
)

func AddonInstallRecord(obj client.Object, addonName, addonVersion string, err error) func() {
	if config.MetricsAddr == "0" {
		return func() { return }
	}

	startTime := time.Now()

	return func() {
		bkemetrics.MetricRegister.RecordGaugeVec(
			bkemetrics.AddonInstallDurationSeconds,
			utils.ClientObjNS(obj),
			fmt.Sprintf("%s-%s", addonName, addonVersion),
			bkemetrics.FormatTime(startTime),
			bkemetrics.TimeNow(),
		).Set(time.Since(startTime).Seconds())

		if err != nil {
			bkemetrics.MetricRegister.RecordCounterVec(
				bkemetrics.AddonInstallFailedCount,
				utils.ClientObjNS(obj),
			).Inc()

		} else {
			bkemetrics.MetricRegister.RecordCounterVec(
				bkemetrics.AddonInstallSuccessCount,
				utils.ClientObjNS(obj),
			).Inc()
		}

		bkemetrics.MetricRegister.RecordCounterVec(
			bkemetrics.AddonInstallCount,
			utils.ClientObjNS(obj),
		).Inc()

	}

}
